package gr.unipi.cinema;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class Movie {
	
	public static Calendar dateToCalendar(Date date) { 
		  Calendar cal = Calendar.getInstance();
		  cal.setTime(date);
		  return cal;
	}
	
	public static MovieData[] getMovieData(int id, String qStr, int state) {
		MovieData[] res = null;
		Connection connection = SqlConnection.getConnection();
		if (connection == null) {
			System.out.println("Cloud not connect to db");
			return res;
		}
		
		Statement st = null;
		ResultSet resultSet = null;
		
		try {
			st = connection.createStatement();
			
			String sql =
					"SELECT ID, MOVIETITLE, SECONDNAME, RELEASEDATE, DESCR, MOVIEORIGIN, MOVIEDUR, IMAGEURL, MOVIESTATE " +
					"FROM CMOVIE " +
					"WHERE ";
			
			sql = sql + " (MOVIESTATE = " + state +") ";
			
			if (id != 0) {
				sql = sql + "AND (ID = " + id + ") ";
			}
			
			if ((qStr != null) && (qStr.length() > 0)) {
				sql = sql + "AND ( (MOVIETITLE LIKE '%" + qStr + "%') OR (SECONDNAME LIKE '%" + qStr +"%') OR (DESCR LIKE '%" + qStr +"%') ) ";
			}
			
			sql = sql + " ORDER BY MOVIETITLE ";
			
			System.out.println("Executing query: " + sql);
			
			resultSet = st.executeQuery(sql);
			
			ArrayList<MovieData> thList = new ArrayList<>(5);
			MovieData entry = null;
			
			while (resultSet.next()) {
				entry = new MovieData(resultSet.getInt("ID"),
										resultSet.getString("MOVIETITLE"),
										resultSet.getString("SECONDNAME"),
										dateToCalendar(resultSet.getDate("RELEASEDATE")),
										resultSet.getString("DESCR"),
										resultSet.getString("MOVIEORIGIN"),
										resultSet.getInt("MOVIEDUR"),
										resultSet.getString("IMAGEURL"),
										resultSet.getInt("MOVIESTATE"));

				thList.add(entry);
			}
			
			res = thList.toArray(new MovieData[0]);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally {
			
			if (resultSet != null) {
				try {
					resultSet.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
				resultSet = null;
			}
			
			if (st != null) {
				try {
					st.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
				st = null;
			}
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			connection = null;
		}
		
		return res;
	}
	
}
